package com.didispace.exception;

import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.didispace.entity.ErrorInfo;

@ControllerAdvice//定义统一的异常处理类
public class GlobalExceptionHandler {
	
	public static final String ERROR_VIEW_NAME = "error";
	
	@ExceptionHandler(Exception.class)//用来定义函数针对的异常类型
	public ModelAndView defaulErrorHandler(HttpServletRequest req,Exception e) throws Exception{
		ModelAndView mv = new ModelAndView();
		mv.addObject("exception",e);
		mv.addObject("url", req.getRequestURL());
		mv.setViewName(ERROR_VIEW_NAME);
		e.printStackTrace();
		return mv;
	}
	
	@SuppressWarnings("static-access")
	@ExceptionHandler(MyException.class)
	@ResponseBody
	public  ErrorInfo<String> jsonErrorHandler(HttpServletRequest req,MyException e) {
		ErrorInfo<String> error = new ErrorInfo<String>();
		error.setCode(error.getError());
		error.setUrl(req.getRequestURL().toString());
		error.setMessage(e.getMessage());
		error.setData("This is data");
		return error;
	}
}
